package raft

import (
	"fmt"
	"log"
	"os"
	"sync"
)

// Debugging
const Debug = 0

func GetMin(a...int) int{
	if len(a) == 0{
		log.Fatalln("GetMin args ERROR!!")
	}
	min:=a[0]
	for i:=1; i<len(a); i++{
		if min > a[i]{
			min = a[i]
		}
	}
	return min
}

func DPrintf(format string, a ...interface{}) (n int, err error) {
	if Debug > 0 {
		log.Printf(format, a...)
	}
	return
}

var DEBUG = true

var mu sync.Mutex

func (rf *Raft) Fprint(strs ...string) {
	if !DEBUG {
		return
	}
	mu.Lock()
	defer mu.Unlock()
	me := rf.me
	file, err := os.OpenFile(fmt.Sprintf("debugInfo_%d", me), os.O_CREATE|os.O_RDWR|os.O_APPEND, 0666)
	if err != nil {
		fmt.Println("OpenFile Err", err)
		return
	}
	defer file.Close()
	str := ""
	for i := 0; i < len(strs); i++ {
		str += strs[i]
	}
	_, err = file.WriteString(str)
	if err != nil {
		fmt.Println("WriteFile Err", err)
		return
	}
}

func Fprint(str string) {
	file0, err := os.OpenFile(fmt.Sprintf("debugInfo_0"), os.O_CREATE|os.O_RDWR|os.O_APPEND, 0666)
	if err != nil {
		fmt.Println("OpenFile0 Err", err)
		return
	}
	file1, err := os.OpenFile(fmt.Sprintf("debugInfo_1"), os.O_CREATE|os.O_RDWR|os.O_APPEND, 0666)
	if err != nil {
		fmt.Println("OpenFile1 Err", err)
		return
	}
	file2, err := os.OpenFile(fmt.Sprintf("debugInfo_2"), os.O_CREATE|os.O_RDWR|os.O_APPEND, 0666)
	if err != nil {
		fmt.Println("OpenFile2 Err", err)
		return
	}
	defer file0.Close()
	defer file1.Close()
	defer file2.Close()

	_, err = file0.WriteString(str)
	if err != nil {
		fmt.Println("WriteFile Err", err)
		return
	}
	_, err = file1.WriteString(str)
	if err != nil {
		fmt.Println("WriteFile Err", err)
		return
	}
	_, err = file2.WriteString(str)
	if err != nil {
		fmt.Println("WriteFile Err", err)
		return
	}
}
